<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\GoodsSku;
use app\common\model\UserReserve;
use think\Config;
use think\Loader;
use think\Request;
use think\Validate;
use think\cache\driver\Redis;
/**
 * 购物车
 */
class Cart extends Api {
    protected $noNeedLogin = ['*'];//空代表都需要验证
    protected $noNeedRight = ['*'];

    /**
    添加购物车
     *
     */
    public function addGoods(){

        $userId = $this->auth->id;
        $goods_id=input('goods_id');
        $sku_id=input('sku_id');
        $buy_num=input('buys_num');
        $type=input('type',0);
        if (!$goods_id&&!$sku_id&&!$buy_num){
            $this->error('参数不完整');
        }
        if($buy_num<=0){

            $this->error('数量不可为0');
        }


        //判断购物车的商品数量是否超过实际商品数量
        $skuInfo=GoodsSku::get(['id'=>$sku_id,'gid'=>$goods_id]);
        if (empty($skuInfo)){

            $this->error('无效的规格');

        }
//        $goods=\app\common\model\Goods::get($goods_id);
//        if($goods['shop_id']==$userId){
//            $this->error('自己不可购买自己商品');
//        }

        if ($skuInfo['deletetime']!=null){

            $this->error('当前商品规格已删除，请刷新');
        }
        if ($skuInfo['sku_stock']<=$buy_num){
            $this->error('库存不足');
        }
        $Cache=new Redis();
        $redis = $Cache->handler();

//        $redis_key= $goodsInfo['is_checking']==2?'shop_cart_'.$userId:'shop_cart_'.$userId.'is_checking';
        $redis_key= 'fubao_shop_cart_'.$userId.'_'.$type;
        $hash_key = $goods_id . '_' . $sku_id;
        if ($redis->hexists($redis_key, $hash_key)) {//判断是否之前添加过
            $redis->hincrby($redis_key, $hash_key, $buy_num);
            if ($redis->hget($redis_key, $hash_key) == 0) {
                $redis->hdel($redis_key, $hash_key);
            }
        } else {
            $redis->hset($redis_key, $hash_key, $buy_num);
        }
        $this->success('添加成功!', null);
    }
    /**
     * 获取购物车数据
     */
    public function getShopCart(){
//        $type=input('type/d',1);//1是普通商品2是检查项目
        $userId = $this->auth->id;
        $Cache=new Redis();
        $redis = $Cache->handler();
//        $redis_key= $type==2?'shop_cart_'.$userId.'is_checking':'shop_cart_'.$userId;
        $redis_key= 'fubao_shop_cart_'.$userId.'_0';
        $goods_info =array_reverse($redis->hkeys($redis_key));
        if (empty($goods_info)){
            $this->success('请求成功!', ['list'=>[]]);
        }
        $spec_count_map = [];
        $spec_ids = [];
        foreach ($goods_info as $keys => $values) {
            $g_con = explode('_', $values);
            $goods_id = $g_con[0];
            $sku_id = $g_con[1];
            $buys_num = $redis->hget($redis_key, $values);
            $ret[$keys]['goods_id'] = $goods_id;
            $ret[$keys]['sku_id'] = $sku_id;
            $ret[$keys]['buys_num'] = $buys_num;
            $spec_count_map[$sku_id] = $buys_num;
            $spec_ids[] = $sku_id;

        }
        //获取商品信息
        $goodsSku=new GoodsSku();

        $goodsList=$goodsSku->getGoodsList($spec_ids);
        if (empty($goodsList)){
            $this->success('请求成功!', ['list'=>[]]);
        }

        $goods_ids = assoc_unique($ret, 'goods_id');
        $goods_ids_arr=array_column($goods_ids,'goods_id');//二维数组转一维数组

        $goodsModel= model('app\common\model\Goods');
        $shop_ids=$goodsModel->with(['admin'])->whereIn('goods.id',$goods_ids_arr)->select();//查询商家

        foreach ($shop_ids as $row) {
            $row->visible(['id', 'shop_id']);
            $row->visible(['admin']);
            $row->getRelation('admin')->visible(['company_name','logo']);
        }

        $shop_ids=toArray($shop_ids);
        $shop_ids = assoc_unique($shop_ids, 'shop_id');
        // 购买数量
        $argv=[];
        foreach ($shop_ids as $k=>$v){

            $argv[$k]['shop_name']=$v['admin']['company_name'];
            $argv[$k]['avatar']=$v['admin']['logo'];
            $argv[$k]['shop_id']=$v['shop_id'];
            $shop_price=0;
            $canPay=1;//1 可以 0 不可以
            foreach ($goodsList as $key => &$goods){
                $goods['buy_num'] = $spec_count_map[$goods['id']];
                $goods['thumbnailimage']=get_app_image_url($goods['thumbnailimage']);
                if ($goods['shop_id']==$v['shop_id']){
                    $goods['all_price']=bcmul( $goods['price'],$goods['buy_num'],2);
                    $goods['sku_id'] = $goods['id'];
                    if($goods['type']==1 || $goods['type']==2){
                        if($goods['starttime']>time()){
                            $canPay = 0;
                        }
                        if($goods['endtime']<time()){
                            $canPay = 0;
                        }
                        if($goods['type1time']>time()){
                            $canPay = 0;
                        }

                    }
                    $goods['canPay'] = $canPay;
                    $argv[$k]['goods'][]=$goods;
//                    $argv[$k]['goods']['sku_id']=$goods['id'];
                    $shop_price+=bcmul($goods['price'],$goods['buy_num'],2);

                }
//                $argv[$k]['type'] = $goods['type'];
                $argv[$k]['shop_price']=$shop_price;


            }
            if (!isset($argv[$k]['goods'])){
               unset( $argv[$k]);
            }
        }
        $this->success('请求成功!', ['list'=>$argv]);

    }
    /**
     * 修改购物车商品数量
     */
    public function updateCartNum(){
//        $type=input('type/d',1);//1是普通商品2是检查项目
        $userId = $this->auth->id;
        $goods_id=input('goods_id/d');
        $sku_id=input('sku_id');
        $buy_num=input('buys_num/d');
        if (!$goods_id&&!$sku_id&&!$buy_num){

            $this->error('参数不完整');
        }
        if ($buy_num<=0){

            $this->error('数量不可为0');
        }

        $Cache=new Redis();
        $redis = $Cache->handler();
//        $redis_key= $type==2?'shop_cart_'.$userId.'is_checking':'shop_cart_'.$userId;
        $redis_key= 'fubao_shop_cart_'.$userId.'_0';
        $hash_key = $goods_id . '_' . $sku_id;
        $redis->hset($redis_key, $hash_key, $buy_num);
        $this->success('修改成功!', null);
    }
    /**
     * 删除购物车
     */
    public function delShopCart(){
        $userId = $this->auth->id;
        $sku_ids=input('sku_ids');
//        $type=input('type/d',1);//1是普通商品2是检查项目

        $Cache=new Redis();
        $redis = $Cache->handler();
//        $redis_key= $type==2?'shop_cart_'.$userId.'is_checking':'shop_cart_'.$userId;
        $redis_key= 'fubao_shop_cart_'.$userId.'_0';

        $goods_info =array_reverse($redis->hkeys($redis_key));
        foreach ($goods_info as $keys => $values) {
            $g_con = explode('_', $values);
            $goods_id = $g_con[0];
            $sku_id = $g_con[1];
            $sku_arr=explode(',',$sku_ids);
            foreach ($sku_arr as $ke=>$va){
                if ($sku_id==$va){
                    $hash_key = $goods_id . '_' . $sku_id;
                    $redis->hdel($redis_key, $hash_key);
                }
            }
        }
        $UserReserve = UserReserve::where(['sku_id'=>$sku_ids])->delete();

        $this->success('删除成功!', null);

    }
    /*
     * 购物车种类数量
     * */
    public function CartNum(){
        $userId = $this->auth->id;
        if(!$userId){
            $this->success('请求成功!', ['num'=>'']);
        }
        $Cache=new Redis();
        $redis = $Cache->handler();
//        $redis_key= $type==2?'shop_cart_'.$userId.'is_checking':'shop_cart_'.$userId;
        $redis_key= 'fubao_shop_cart_'.$userId.'_0';

        $goods_info =array_reverse($redis->hkeys($redis_key));
        if (empty($goods_info)){
            $this->success('请求成功!', ['num'=>'']);
        }

        $this->success('请求成功!', ['num'=>count($goods_info)]);
    }

}